#include "Data_Reporter.h"
struct Data_Reporter_config config;

void write_file(char *data)
{
    int fd;
    fd = open("/mnt/config/node.json", O_RDWR | O_TRUNC);
    if (fd < 0)
    {
        perror("error");
        return;
    }
    int writelen = write(fd, data, sizeof(data));
    if(writelen < 0)
    {
        perror("error");
        return;
    }
    close(fd);
}

int init_reporter()
{
    //判断json点表是否存在——是否初始化
    if (access("/mnt/config/node.json", F_OK) == 0)
    {
        printf("点表存在！\n");
        config.is_nodefile = true;
    }
    else
    {
        printf("点表不存在！\n");
        config.is_nodefile = false;
    }

    int broadfd;

    //创建一个socket文件描述符
    broadfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(broadfd < 0)
    {
        perror("sock err");
        return -1;
    }

    //绑定套接字(ip+port)
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8888);  //端口号
    addr.sin_addr.s_addr = INADDR_ANY;

    int addrlen = sizeof(addr);
    
    if(bind(broadfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        return -1;
    }

    ssize_t len;
    char buf[N] = {0};
    struct sockaddr_in cliaddr;
    
    //接收"coffee"搜索包
    bzero(buf, N);
    len = recvfrom(broadfd, buf, N, 0, (struct sockaddr *)&cliaddr, (socklen_t *)&addrlen);
    if(len < 0)
    {
        printf("recv err\n");
        return -1;
    }

    //判断是否是本公司产品：收到的数据是否"coffee"
    if(strcmp(buf, "sixgroup") != 0)
    {
        printf("not my sixgroup\n");
        return -1;
    }

    //回复yes，告诉软件，我收到了搜索协议，并且回复地址
    sendto(broadfd, "yes", 4, 0, (struct sockaddr *)&cliaddr, addrlen);

    //变身为TCP服务器，准备接收软件的升级文件
    int tcpfd = socket(AF_INET, SOCK_STREAM, 0);
    if(tcpfd < 0)
    {
        perror("sock err");
        return -1;
    }

    if(bind(tcpfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        return -1;
    }

    //监听套接字
    if(listen(tcpfd, 5) < 0)
    {
        perror("listen err");
        return -1;
    }

    //接收客户端的连接
    printf("wait client connect\n");
    int clifd;
    
    //接收对端的地址
    clifd = accept(tcpfd, NULL, NULL);
    if(clifd < 0)
    {
        perror("accept err");
        return -1;
    }

    printf("new cononect coming\n");    

    //5、接收点表数据数据
    char get_buf[2048] = {0};
    int s = recv(clifd, get_buf, 2048, MSG_DONTWAIT);
    /* 
    if (s < 0)
    {
        perror("rec err");
        return -1;
    }
    else if (s == 0)
    {
        printf("client exit\n");
        buf[0] = '\0';
        return -1;
    }*/
    printf("%s\n", get_buf);
    //printf("new cononect coming\n");
    close(tcpfd);
    close(broadfd);
    return 0;
}